package com.csdn.leon.fragment;

import java.io.ByteArrayInputStream;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;

import butterknife.ButterKnife;
import butterknife.InjectView;

import com.csdn.leon.activity.BlogCloumnListActivity;
import com.csdn.leon.activity.BlogContentActivity;
import com.csdn.leon.activity.BlogDetailActivity;
import com.csdn.leon.activity.BlogHostActivity;
import com.csdn.leon.adapter.BlogAdapter;
import com.csdn.leon.anima.AnimatorUtil;
import com.csdn.leon.base.ListBaseAdapter;
import com.csdn.leon.cache.AsycTaskUtil;
import com.csdn.leon.cache.AsycTaskUtil.TaskCompletdListener;
import com.csdn.leon.cache.CacheManager;
import com.csdn.leon.db.DBUtil;
import com.csdn.leon.interf.ActivityListener;
import com.csdn.leon.model.BlogModel;
import com.csdn.leon.model.CloumnModel;
import com.csdn.leon.model.CommonList;
import com.csdn.leon.model.ListEntity;
import com.csdn.leon.model.Person;
import com.csdn.leon.net.CSDNapi;
import com.csdn.leon.util.JsoupUtil;
import com.csdn.leon.util.ListHelpUtil;
import com.csdn.leon.util.StringUtils;
import com.csdn.leon.util.TDevice;
import com.csdn.leon.util.URLUtil;
import com.csdn.leon.view.EmptyLayout;
import com.csdn.leon.view.dialog.ClickedItemDialog;
import com.csdn.leon.view.dialog.DialogHelper;
import com.csdn.leon.view.dialog.ClickedItemDialog.HomeDialogListener;
import com.csdn.leon.view.dialog.WaitDialog;
import com.csdn.leon.view.popup.FloatPopupWindow;
import com.csdn.leon.view.swipyrefreshlayout.SwipyRefreshLayout;
import com.csdn.leon.view.swipyrefreshlayout.SwipyRefreshLayout.OnRefreshListener;
import com.csdn.leon.view.swipyrefreshlayout.SwipyRefreshLayoutDirection;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.TextHttpResponseHandler;
import com.csdn.leon.base.R;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

public class HomeFragment extends BaseFragment implements OnRefreshListener,
		OnScrollListener, OnItemClickListener, TaskCompletdListener,
		OnItemLongClickListener {

	private final String TAG = HomeFragment.class.getSimpleName();
	public final static String TITLE = "首页";
	public static final int REFRESH_DELAY = 2000;
	public int blogType = 1;
	protected int mCurrentPage = 1;
	private AsyncTask<String, Void, CommonList<BlogModel>> mCacheTask;
	protected String url;
	public static SwipyRefreshLayout mSwipyRefreshLayout;
	Map<String, Integer> map;
	private BlogAdapter blogAdapter;
	private ListView listView;
	private View view;
	private Activity activity;
	protected ListView mListView;
	protected EmptyLayout mErrorLayout;
	private ParserTask mParserTask;
	private ActivityListener activityListener;
	private ImageView floatBtn;

	private WaitDialog dialog;
	int touchSlop = 10;
	private boolean isNew = false;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.activity = activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(true);// 保留fragment对象
	}

	/*
	 * 返回View
	 * 
	 * @see
	 * android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
	 * android.view.ViewGroup, android.os.Bundle)
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		ButterKnife.inject(this, view);
		view = inflater
				.inflate(R.layout.home_fragment_layout, container, false);
		initView();
		requestData(true);
		return view;
	}

	private void initView() {
		dialog = new WaitDialog(activity, R.style.waitDialog,
				R.layout.dialog_wait_layout);
		floatBtn = (ImageView) view.findViewById(R.id.float_btn);
		floatBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// FloatPopupWindow pop = new FloatPopupWindow(activity, v);
				listView.setSelection(0);
			}
		});
		blogAdapter = new BlogAdapter(activity);
		listView = (ListView) view.findViewById(R.id.list_view);
		mErrorLayout = (EmptyLayout) view.findViewById(R.id.error_layout);
		listView.setAdapter(blogAdapter);
		listView.setOnItemClickListener(this);
		listView.setOnItemLongClickListener(this);
		listView.setOnScrollListener(this);
		mSwipyRefreshLayout = (SwipyRefreshLayout) view
				.findViewById(R.id.pull_to_refresh);
		mSwipyRefreshLayout.setOnRefreshListener(this);
		AsycTaskUtil.getInstance().setListeler(this);
		mState = STATE_NONE;
		mErrorLayout.setOnLayoutClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mCurrentPage = 1;
				// mState = STATE_REFRESH;
				// mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
				// requestData(true);
			}
		});
	}

	TextHttpResponseHandler handle = new TextHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, String arg2,
				Throwable arg3) {
			mSwipyRefreshLayout.setRefreshing(false);
			hideWaitDialog();
			Toast.makeText(activity, "加载失败，请重新加载...", 2000).show();
			// mErrorLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
			if (activityListener != null) {
				activityListener.completedRefresh();
			}
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, String s) {
			executeParserTask(s);
		}
	};

	/***
	 * 获取列表数据
	 * 
	 * 
	 * @author leon
	 * 
	 * @return void
	 * @param refresh
	 */
	// 取新的数据
	public void requestData(boolean refresh) {
		//mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
		showWaitDialog();
		String key = StringUtils.getCacheKey(TAG, blogType, mCurrentPage);
		if (AsycTaskUtil.getInstance().isReadCache(activity, TAG, blogType,
				mCurrentPage)
				&& refresh) {
			AsycTaskUtil.getInstance().readBlogModelData(activity, key);
		} else {
			sendRequestData(blogType, refresh);
		}
	}

	protected void sendRequestData(int type, boolean flag) {
		if (activityListener != null) {
			activityListener.startRefresh();
		}
		if (!TDevice.isNetworkAvailable()) {
			mErrorLayout.post(new Runnable() {
				@Override
				public void run() {
					mErrorLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
				}
			});
			return;
		}
		if (flag) {
			url = URLUtil.getBlogListURL(type, isNew);
		} else {
			url = URLUtil.getBlogListURL(blogType,
					String.valueOf(mCurrentPage), true);
		}
		CSDNapi.getBlogList(url, handle);
	}

	@Override
	public void onRefresh(SwipyRefreshLayoutDirection direction) {
		if (direction == SwipyRefreshLayoutDirection.TOP) {
			mCurrentPage = 1;
			sendRequestData(blogType, true);
		} else if (direction == SwipyRefreshLayoutDirection.BOTTOM) {
			mCurrentPage++;
			sendRequestData(blogType, false);
		}
	}

	private void executeParserTask(String data) {
		cancelParserTask();
		mParserTask = new ParserTask(data);
		mParserTask.execute();
	}

	private void cancelParserTask() {
		if (mParserTask != null) {
			mParserTask.cancel(true);
			mParserTask = null;
		}
	}

	class ParserTask extends AsyncTask<Void, Void, String> {

		private final String reponseData;
		private boolean parserError;
		private List<BlogModel> list;

		public ParserTask(String data) {
			this.reponseData = data;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// showWaitDialog();
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				CommonList<BlogModel> commonList = ListHelpUtil
						.paraseBlogModelToList(blogType, reponseData);
				String key = StringUtils.getCacheKey(TAG, blogType,
						mCurrentPage);
				commonList.setCacheKey(key);
				AsycTaskUtil.getInstance().saveData(activity, commonList, key);
				list = commonList.getList();
			} catch (Exception e) {
				e.printStackTrace();
				parserError = true;
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			// hideWaitDialog();
			executeOnLoadDataSuccess(list);
			if (activityListener != null) {
				activityListener.completedRefresh();
			}
		}
	}

	protected void executeOnLoadDataSuccess(List<BlogModel> list) {
		mSwipyRefreshLayout.setRefreshing(false);
		if (list != null) {
			if (mCurrentPage == 1) {
				blogAdapter.setList(list);
			} else {
				blogAdapter.addList(list);
			}
		} else {
			list = new ArrayList<BlogModel>();
		}
		hideWaitDialog();
	}

	private boolean needShowEmptyNoData() {
		return true;
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if (scrollFlag) {
			AnimatorUtil.animateHide(floatBtn);
		} else {
			AnimatorUtil.animateBack(floatBtn);
		}
		lastPosition = firstVisibleItem;
	}

	boolean scrollFlag = false;

	/**
	 * 滑动到底部时是否更新 (non-Javadoc)
	 * 
	 * @see android.widget.AbsListView.OnScrollListener#onScrollStateChanged(android.widget.AbsListView,
	 *      int)
	 */
	int lastPosition = 0;
	int state = AbsListView.OnScrollListener.SCROLL_STATE_IDLE;

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		Log.w("是否到底部", "scrollState:" + scrollState);
		switch (scrollState) {
		// 当不滚动时
		case OnScrollListener.SCROLL_STATE_IDLE:// 是当屏幕停止滚动时
			scrollFlag = false;
			AnimatorUtil.animateBack(floatBtn);
			// 判断滚动到底部
			if (listView.getLastVisiblePosition() == (listView.getCount() - 1)) {
				// toTopBtn.setVisibility(View.VISIBLE);
			}
			// 判断滚动到顶部
			if (listView.getFirstVisiblePosition() == 0) {
				// toTopBtn.setVisibility(View.GONE);
			}
			break;
		case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:// 滚动时
			scrollFlag = true;
			break;
		case OnScrollListener.SCROLL_STATE_FLING:// 是当用户由于之前划动屏幕并抬起手指，屏幕产生惯性滑动时
			scrollFlag = true;
			break;
		}
	}

	public ActivityListener getActivityListener() {
		return activityListener;
	}

	public void setActivityListener(ActivityListener activityListener) {
		this.activityListener = activityListener;
	}

	public boolean isNew() {
		return isNew;
	}

	public void setNew(boolean isNew) {
		this.isNew = isNew;
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View v, int position,
			long id) {
		BlogModel blogModel = blogAdapter.getList().get(position);
		Intent intent = new Intent(activity, BlogContentActivity.class);
		intent.putExtra("blog_url", blogModel.getLink());
		intent.putExtra("blogmodel", blogModel);
		activity.startActivity(intent);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		final BlogModel blogModel = blogAdapter.getList().get(position);
		final ClickedItemDialog dialog = DialogHelper.getItemDialog(activity,
				blogModel.getUsername(), blogModel.getTitle());
		dialog.setListener(new HomeDialogListener() {

			@Override
			public void onClicked(int n, boolean flag) {
				switch (n) {
				case 1:
					dialog.cancel();
					;
					Intent intent = new Intent(activity, BlogHostActivity.class);
					intent.putExtra("username", blogModel.getUsername());
					activity.startActivity(intent);
					break;
				case 2:
					if (flag) {
						DBUtil.deleteBlogModel(activity, blogModel.getTitle());
					} else {
						DBUtil.insertBlogModel(activity, blogModel);
					}
					dialog.cancel();

					break;
				case 3:
					if (flag) {
						DBUtil.deleteHost(activity, blogModel.getUsername());
					} else {
						Person person = new Person();
						person.setUsername(blogModel.getUsername());
						person.setUserface(blogModel.getImgLink());
						DBUtil.insertHost(activity, person);
					}
					dialog.cancel();
					break;
				default:
					dialog.hide();
					break;
				}
			}
		});

		dialog.show();
		return true;
	}

	public int getBlogType() {
		return blogType;
	}

	public void setBlogType(int blogType) {
		this.blogType = blogType;
	}

	@Override
	public void completedBlogModel(List<BlogModel> list) {
		if (list != null) {
			executeOnLoadDataSuccess(list);
		} else {
			executeOnLoadDataSuccess(null);
		}
	}

	@Override
	public void completedCloumnModel(List<CloumnModel> list) {
	}

}
